package com.dcdata.xian;

import com.alibaba.fastjson.JSON;
import com.dcdata.xian.pojo.GjznCard;
import oracle.jdbc.datasource.OracleDataSource;
import oracle.jdbc.replay.OracleDataSourceImpl;

import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author: xinmi
 * @date: 2020/11/19
 * @description:
 */
public class OneRouteReceive {

    private static String user = "GJXWGH";
    private static String password = "GJXWGH20201116";
    private static String url = "jdbc:oracle:thin:@//10.238.161.162:1521/ORCLPDB";

    private static String cardFileName;

    private static String queryDate;

    public static void main(String argv[]) throws SQLException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, - 3);
        Date time = c.getTime();

        queryDate = sdf.format(time);

        if (cardFileName == null || cardFileName.isEmpty()) {
            LocalDate localDate = LocalDate.now();
            cardFileName = System.getProperty("user.dir") + "/data/card/Card" + localDate.toString().replace("-", "_") + ".txt";
        }

        generateFileNameSchedule();

        OneRouteReceive oneRouteReceive = new OneRouteReceive();

        oneRouteReceive.run();

    }

    private static void generateFileNameSchedule(){
        File dataDir = new File(System.getProperty("user.dir") + "/data");
        if (!dataDir.exists() && !dataDir.isDirectory())
            if (!dataDir.mkdir()) {
                System.out.println("mkdir data failed");
            }

        File cardDir = new File(System.getProperty("user.dir") + "/data/card");
        if (!cardDir.exists() && !cardDir.isDirectory())
            if (!cardDir.mkdir()) {
                System.out.println("mkdir data/card failed");
            }

        Timer timer = new Timer();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, Config.GPS_HOUR); //4点
        calendar.set(Calendar.MINUTE, Config.GPS_MINUTE);//45分
        calendar.set(Calendar.SECOND, Config.GPS_SECOND);//0秒
        //每天的凌晨4:45,重新生成新文件
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                //每天定时生成新的文件路径和相应的输出流
                LocalDate localDate = LocalDate.now();
                cardFileName = System.getProperty("user.dir") + "/data/card/Card" + localDate.toString().replace("-", "_") + ".txt";
            }
        }, calendar.getTime(), 24 * 60 * 60 * 1000);
    }

    static Connection getConnection() throws SQLException {
        OracleDataSource ods = new OracleDataSourceImpl();
        ods.setURL(url);
        ods.setUser(user);
        ods.setPassword(password);
        Connection conn = ods.getConnection();
        return conn;
    }



    void run() throws SQLException {
        try (Connection conn = getConnection()) {

            // Truncate the existing table
            show("before receive card table.");
            cardTable(conn);


        }

    }


    private void cardTable(Connection conn) {

        final String to_date = "to_date('"+ queryDate + "','YYYY-MM-DD')";

        final String alert = "ALTER session SET current_schema =  TONGTU;";
        final String sql = "select BUSID, LINEID, USERTYPE, PARSEDATETIME, TRADEDATETIME, PROCESSDATETIME, " +
                "BUSNAME, LINENAME, STATIONNAME, STATIONID, RKSJ, TXNTYPE, CARDID, CARDCSN, POSOPRID, ORIGAMT, " +
                "TXNDATE, TXNTIME, UPTIME, UPBUSID, UPLINEID, UPSTATIONID, ISQR " +
                "FROM TONGTU.GJZN_CARDINFO WHERE TRADEDATETIME > " + to_date;
        final String sql2 = "select * FROM TONGTU.GJZN_CARDINFO";

        try (Statement st = conn.createStatement()) {
            //st.executeQuery(alert);
            try (ResultSet rs = st.executeQuery(sql)) {
                while (rs.next()) {
                    GjznCard gjznCard = new GjznCard();

                    Field[] fields = GjznCard.class.getDeclaredFields();
                    int i = 1;
                    for (Field field : fields) {
                        field.setAccessible(true);
                        if (field.getType().isAssignableFrom(String.class)) {
                            field.set(gjznCard, rs.getString(i));
                        }
                        if (field.getType().isAssignableFrom(Integer.class)) {
                            field.set(gjznCard, rs.getInt(i));
                        }
                        if (field.getType().isAssignableFrom(Date.class)) {
                            field.set(gjznCard, rs.getDate(i));
                        }
                        if (field.getType().isAssignableFrom(BigDecimal.class)) {
                            field.set(gjznCard, rs.getBigDecimal(i));
                        }
                        i++;
                    }
                    show(JSON.toJSON(gjznCard).toString());
                    //this.writeCard(JSON.toJSON(gjznCard).toString());
                }
                show("write card table into local card file successfully.");
            }
        } catch (SQLException | IllegalAccessException e) {
            showError("select card table operation failed or write local card table file failed .", e);
        }
    }

    private  void writeCard(String response) {

        File file = new File(cardFileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file, true);
            byte[] bytes = (response + "\n").getBytes();
            for (byte aByte : bytes) {
                fos.write(aByte);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fos != null;
                fos.flush(); //强制刷新输出流
                fos.close(); //强制关闭输出流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void writeCard2(String words) throws IOException {

        BufferedWriter bw = new BufferedWriter(new FileWriter(cardFileName));
        bw.write(words);
        //刷新流
        bw.flush();
        //关闭资源
        bw.close();
    }


    private static void show(String msg) {
        System.out.println(msg);
    }

    static void showError(String msg, Throwable exc) {
        System.out.println(msg + " hit error: " + exc.getMessage());
    }

}
